<template>
    <div class="layout-route">
        <div class="header"><el-button icon="el-icon-arrow-left" @click="cancel">返回</el-button> <span class="header-title">备货建议明细</span></div>
        <div class="card card-search">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                <el-form-item label="商品sku" prop="seller_sku">
                    <el-input v-model.trim="queryParams.seller_sku" placeholder="请输入商品sku" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="产品分类" prop="spu">
                    <el-select v-model="queryParams.product_type" placeholder="请选择产品分类" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.productType" :key="index" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="热销分类" prop="spu">
                    <el-select v-model="queryParams.hot_type" placeholder="请选择热销分类" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.hotType" :key="index" :label="dict.label" :value="dict.value" />
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="采购者" prop="operate_id">
                    <el-select v-model="queryParams.operate_id" placeholder="请选择采购者" clearable size="small" style="width: 240px">
                        <el-option v-for="(dict, index) in dict.salesmanList" :key="index" :label="dict.username" :value="dict.operater_id" />
                    </el-select>
                </el-form-item> -->
                <el-form-item label="供应商" prop="supply_id">
                    <SelectPage
                        v-model="queryParams.supply_id"
                        placeholder="请选择供应商"
                        :url="$api.supply.getSupplyList"
                        show_field="supply_name"
                        query_field="supply_name"
                        query_field2="spu"
                        filterable
                        clearable
                        popper-class="custom-select"
                        style="width: 240px"
                    ></SelectPage>
                </el-form-item>
                <el-form-item label="创建时间" prop="create_time">
                    <el-date-picker v-model="queryParams.create_time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label=" ">
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="el-icon-download" :loading="download" :disabled="download" @click="handleExport">导出</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table
                ref="sortTable"
                v-loading="loading"
                :data="tableData"
                row-key="id"
                border
                script
                default-expand-all
                :span-method="arraySpanMethod"
                @sort-change="handleSortChange"
                class="expend-table"
            >
                <el-table-column label="" type="expand" width="50">
                    <template slot-scope="scope">
                        <el-table :data="scope.row.sku_info" border :show-header="false" class="sub-table">
                            <el-table-column label="商品信息" prop="order_id" min-width="250">
                                <template slot-scope="subScope">
                                    <div class="flex">
                                        <div style="width: 70px">
                                            <ImageUploadImg v-model="subScope.row.image_url" :readOnly="true" class="small-img"></ImageUploadImg>
                                        </div>
                                        <div>
                                            <!-- @click="showSkuListDialog(subScope.row)" -->
                                            <el-link type="primary">{{ subScope.row.seller_sku }}</el-link>
                                            <div>{{ subScope.row.hot_type | formatLabelByValueFuzzy(dict.hotType) }}</div>
                                            <div>{{ subScope.row.product_type | formatLabelByValueFuzzy(dict.productType) }}</div>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="库存" min-width="100" prop="inventory_quantity" align="center"></el-table-column>
                            <el-table-column label="在途" min-width="100" prop="on_way_quantity" align="center"></el-table-column>
                            <el-table-column label="订单" min-width="100" prop="not_send_quantity" align="center"></el-table-column>
                            <el-table-column label="货期" min-width="140" prop="produce_days" align="center">
                                <template slot-scope="subScope">
                                    <span slot="reference" @click="showEditPopover(subScope.row, scope.$index)" v-if="!subScope.row.edit">
                                        {{ subScope.row.produce_days }}
                                        <i class="el-icon-edit-outline" ref="editBtn" style="color: #11a983"></i>
                                    </span>
                                    <div class="flex items-center justify-between" v-else>
                                        <el-input
                                            v-model="editModal.produce_days"
                                            :autofocus="true"
                                            @blur="editBlur(subScope.row, scope.$index)"
                                            placeholder="请输入"
                                            size="mini"
                                            style="width: 80px"
                                            v-if="subScope.row.edit"
                                        ></el-input>
                                        <el-button size="mini" type="text" style="padding: 7px 4px" @click="updatePurchaseQuantity('produce_days')">确定</el-button>
                                        <el-button size="mini" type="text" style="margin-left: 0" @click="hideEditPopover(subScope.row, scope.$index)">取消</el-button>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="安全" min-width="100" prop="safe_quantity" align="center"></el-table-column>
                            <el-table-column label="备货" min-width="100" prop="suggest_days" align="center"></el-table-column>
                            <el-table-column label="日均" min-width="100" prop="sku_1days" align="center"></el-table-column>
                            <el-table-column label="3/7/15/30" min-width="120" prop="_3/7/15/30" align="center">
                                <template slot-scope="subScope">{{ subScope.row.sku_3days }}/{{ subScope.row.sku_7days }}/{{ subScope.row.sku_15days }}/{{ subScope.row.sku_30days }} </template>
                            </el-table-column>
                            <el-table-column label="建议备货量" min-width="140" prop="suggest_sku_nums" align="center">
                                <template slot-scope="subScope">
                                    <div class="flex column align-center">
                                        <el-tooltip placement="top" effect="light">
                                            <div slot="content">
                                                <div style="margin-bottom: 4px">建议数量 =（订单量+安全库存） - （在途+库存） - 采购计划中</div>
                                                <div>
                                                    {{
                                                        `${subScope.row.suggest_quantity} =（${subScope.row.sku_1days}+${subScope.row.safe_quantity}）-（${subScope.row.on_way_quantity}+${subScope.row.inventory_quantity}）-  ${subScope.row.pre_suggest_quantity}`
                                                    }}
                                                </div>
                                            </div>
                                            <div style="color: #f40">{{ subScope.row.suggest_quantity }}</div>
                                        </el-tooltip>

                                        <div ref="editPopover">
                                            <span slot="reference" @click="showEditPopover(subScope.row, scope.$index)" v-if="!subScope.row.edit">
                                                {{ subScope.row.suggest_sku_nums }}
                                                <i class="el-icon-edit-outline" ref="editBtn" style="color: #11a983"></i>
                                            </span>
                                            <div class="flex items-center justify-between" v-else>
                                                <el-input
                                                    v-model="editModal.suggest_sku_nums"
                                                    :autofocus="true"
                                                    @blur="editBlur(subScope.row, scope.$index)"
                                                    placeholder="请输入"
                                                    size="mini"
                                                    style="width: 80px"
                                                    v-if="subScope.row.edit"
                                                ></el-input>
                                                <el-button size="mini" type="text" style="padding: 7px 4px" @click="updatePurchaseQuantity('suggest_sku_nums')">确定</el-button>
                                                <el-button size="mini" type="text" style="margin-left: 0" @click="hideEditPopover(subScope.row, scope.$index)">取消</el-button>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="采购员" min-width="120">
                                <template slot-scope="subScope">
                                    <span :style="{ color: subScope.row.remark_color == 1 ? '#c03639' : '#30b08f' }">{{ subScope.row.remark }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="创建时间" min-width="160" prop="create_time" align="center"></el-table-column>
                            <el-table-column label="操作" width="120">
                                <template slot-scope="subScope">
                                    <div><el-button type="text" style="padding: 4px 0" @click="addRemark(subScope.row)">备注</el-button></div>
                                    <div><el-button type="text" style="padding: 4px 0" @click="deletePlanSuggest(subScope.row)">删除</el-button></div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
                <el-table-column label="商品信息" prop="order_id" min-width="200">
                    <template slot-scope="scope">
                        <div class="flex">
                            <span style="position: relative; padding-right: 36px">
                                供应商：{{ scope.row.supply_name }}
                                <!-- <sub style="font-size: 12px; color: #ffba00; position: absolute; right: 8px; top: -4px">1688</sub> -->
                            </span>

                            <!-- <el-link type="warning">一键生成采购订单</el-link> -->
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="基础数据" align="center">
                    <el-table-column label="库存" min-width="100" align="center" prop="inventory_quantity" sortable="custom" :sort-orders="['descending', 'ascending']">
                        <template #header>
                            <el-tooltip content="库存总数" placement="top">
                                <!-- <div>
                                    <span>库存</span>
                                    <i class="el-icon-question"></i>
                                </div> -->
                                <el-link type="info">库存</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="在途" min-width="100" align="center" prop="on_way_quantity" sortable="custom" :sort-orders="['descending', 'ascending']">
                        <template #header>
                            <el-tooltip content="sku已下单未入库的数量" placement="top">
                                <el-link type="info">在途</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="订单" min-width="100" align="center" prop="not_send_quantity" sortable="custom" :sort-orders="['descending', 'ascending']">
                        <template #header>
                            <el-tooltip content="未发订单中需要sku的数量" placement="top">
                                <el-link type="info">订单</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table-column>

                <el-table-column label="智能预测备货量" align="center">
                    <el-table-column label="货期" min-width="140" align="center">
                        <template #header>
                            <el-tooltip content="工厂做货周期" placement="top">
                                <el-link type="info">货期</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="安全" min-width="100" align="center">
                        <template #header>
                            <el-tooltip content="平均日销*备货天数" placement="top">
                                <el-link type="info">安全</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="备货" min-width="100" align="center">
                        <template #header>
                            <el-tooltip content="根据产品热销类型设置的备货天数" placement="top">
                                <el-link type="info">备货</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="日均" min-width="100" align="center" prop="sku_1days" sortable="custom" :sort-orders="['descending', 'ascending']">
                        <template #header>
                            <el-tooltip content="根据产品热销类型备货天数内的评均销量" placement="top">
                                <el-link type="info">日均</el-link>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="3/7/15/30" min-width="120" align="center"></el-table-column>
                </el-table-column>
                <el-table-column label="建议备货量" min-width="140" align="center" prop="suggest_sku_nums" sortable="custom" :sort-orders="['descending', 'ascending']">
                    <template #header>
                        <el-tooltip content="平均日销*(货期+物流+安全库存天数)+订单未发-(在途+总库存)" placement="top">
                            <el-link type="info">建议备货量</el-link>
                        </el-tooltip>
                    </template>
                    <template slot-scope="scope">
                        <div style="text-align: left">SKU种类：{{ scope.row.sku_nums }}，商品总数：{{ scope.row.sku_quantity }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="备注" min-width="120"></el-table-column>
                <el-table-column label="创建时间" min-width="160" align="center"></el-table-column>
                <el-table-column label="操作" width="120"></el-table-column>
            </el-table>
            <!-- <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList" /> -->
        </div>
        <RemarkDialog v-model="remarkDialog.visible" :params="remarkDialog.data" @success="handleQuery"></RemarkDialog>
    </div>
</template>
<script>
import { getPlanSuggest, deletePlanSuggest, editPlanSuggest, editSuggestSkuNums, getPurchaserList, exportSkuList } from '@/api/purchase'
import { parseTime } from '@/utils/quickadmin'
import { exportFile } from '@/utils/index'
import RemarkDialog from './components/remarkDialog.vue'
export default {
    name: 'PurchaseSuggest',
    components: { RemarkDialog },
    props: {
        params: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        return {
            cartVisible: false,
            // 遮罩层
            loading: true,
            download: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            total_normal: 0,
            total_not: 0,

            // 状态数据字典
            dict: {
                salesmanList: [],
                productType: [
                    { label: 'bar类型', value: 1 },
                    { label: 'shapewear类型', value: 2 },
                    { label: 'swim类型', value: 3 },
                    { label: 'panties类型', value: 4 },
                    { label: '其他', value: 5 },
                ],
                hotType: [
                    { label: '热销', value: 1 },
                    { label: '潜力款', value: 2 },
                    { label: '新品', value: 3 },
                    { label: '中长尾款', value: 4 },
                ],
            },
            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 查询参数
            queryParams: {
                product_type: undefined,
                seller_sku: undefined,
                hot_type: undefined,
                spu: undefined,
                operate_id: undefined,
                supply_id: undefined,
                create_time: [],
                inventory_quantity: undefined,
                on_way_quantity: undefined,
                not_send_quantity: undefined,
                sku_1days: undefined,
                suggest_sku_nums: undefined,
            },
            syncDialog: {
                visible: false,
                data: {},
            },
            remarkDialog: {
                visible: false,
                data: {},
            },
            changeSupplyDialog: {
                visible: false,
                data: {},
            },
            editModal: {
                id: '',
                suggest_sku_nums: '',
                produce_days: '',
            },
            editData: {
                visible: false,
                data: {},
            },
            cartPosition: { x: 0, y: 0 },
            cartCount: 0,
        }
    },
    watch: {
        params: {
            handler(val) {
                if (val.spu) {
                    this.getList()
                }
            },
            immediate: true,
        },
    },
    async created() {
        this.loading = true
        try {
            const salesmanData = await getPurchaserList()
            this.dict.salesmanList = salesmanData?.data ?? []
        } catch (error) {
            this.loading = false
        }
    },

    methods: {
        cancel() {
            this.$emit('cancel')
        },
        handleExport() {
            this.download = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            exportSkuList(qyparams)
                .then(res => {
                    exportFile(res, () => {
                        this.download = false
                    })
                })
                .catch(err => {
                    console.log(err)
                    this.download = false
                })
        },
        showSkuListDialog(row) {
            this.editData.visible = true
            this.editData.data = row
        },
        resetSort() {
            this.queryParams.inventory_quantity = undefined
            this.queryParams.on_way_quantity = undefined
            this.queryParams.not_send_quantity = undefined
            this.queryParams.sku_1days = undefined
            this.queryParams.suggest_sku_nums = undefined
        },
        handleSortChange({ column, prop, order }) {
            this.resetSort()
            this.queryParams[prop] = order === 'descending' ? 'desc' : order === 'ascending' ? 'asc' : undefined
            this.getList()
        },
        addRemark(row) {
            this.remarkDialog.visible = true
            this.remarkDialog.data = row
        },
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 1) {
                return [1, 10]
            } else if (columnIndex == 12 || columnIndex == 13) {
                return [1, 1]
            } else if (columnIndex == 10) {
                return [1, 3]
            } else {
                return [0, 0]
            }
        },
        //列表
        getList() {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
                spu: this.params.spu,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            getPlanSuggest(qyparams)
                .then(response => {
                    this.tableData = response.data.list
                    this.total = response.data.total
                    // 根据tableData.sku_info的长度，初始化edit
                    this.tableData.map((temp, index) => {
                        temp.id = temp.id || temp.supply_name + '--' + index
                        temp.sku_info.forEach(item => {
                            item.edit = false
                            return { ...item }
                        })
                    })
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')
            this.resetSort()
            this.$refs.sortTable.clearSort()
            this.handleQuery()
        },
        showEditModal(row) {
            this.changeSupplyDialog.visible = true
            this.changeSupplyDialog.data = row
        },

        // 删除按钮操作
        deletePlanSuggest(row) {
            this.$confirm('是否确认删除?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    await deletePlanSuggest({ id: row.id })
                    this.getList()
                    this.msgSuccess('操作成功')
                })
                .catch(() => {})
        },
        showEditPopover(row, $index) {
            const updatedSkuInfo = this.tableData[$index].sku_info.map(item => {
                if (item.id === row.id) {
                    return { ...item, edit: true }
                } else {
                    return { ...item, edit: false }
                }
            })
            // 替换原数组
            this.$set(this.tableData[$index], 'sku_info', updatedSkuInfo)

            this.editModal.id = row.id
            this.editModal.suggest_sku_nums = row.suggest_sku_nums
            this.editModal.produce_days = row.produce_days
        },
        editBlur(row, $index) {
            setTimeout(() => {
                this.hideEditPopover(row, $index)
            }, 500)
        },
        hideEditPopover(row, $index) {
            const updatedSkuInfo = this.tableData[$index].sku_info.map(item => {
                return { ...item, edit: false }
            })
            // 替换原数组
            this.$set(this.tableData[$index], 'sku_info', updatedSkuInfo)

            this.editModal.id = ''
            this.editModal.suggest_sku_nums = ''
            this.editModal.produce_days = ''
        },

        updatePurchaseQuantity(type) {
            const request = type === 'suggest_sku_nums' ? editPlanSuggest : editSuggestSkuNums
            const params = Object.assign({}, this.editModal)
            if (type === 'produce_days') {
                delete params.suggest_sku_nums
            }
            if (type === 'suggest_sku_nums') {
                delete params.produce_days
            }
            request(params).then(res => {
                this.msgSuccess('操作成功')
                this.getList()
            })
        },
    },
}
</script>
<style scoped>
.ball {
    display: block;
    position: fixed;
    width: 20px; /* 小球的宽度 */
    height: 20px; /* 小球的高度 */
    background-color: #f40; /* 小球的颜色 */
    border-radius: 50%; /* 圆形 */
    z-index: 9999; /* 确保在最上层 */
    pointer-events: none; /* 防止干扰点击事件 */
    opacity: 1; /* 确保初始可见 */
    transition: all 0.6s cubic-bezier(0.49, -0.29, 0.75, 0.41); /* 动画效果 */
}
::v-deep .expend-table .el-table__expanded-cell[class*='cell'] {
    padding: 0 !important;
}
.custom-select .el-select-dropdown__item {
    max-width: 450px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.border-cell {
    padding: 0 !important;
}
.border-cell .cell {
    padding: 0 !important;
}
.border-cell-item {
    padding: 10px;
    border-bottom: 1px solid #dfe6ec;
}
.border-cell-item:last-child {
    border-bottom: 0;
}
.el-tabs--border-card {
    box-shadow: none;
    border-bottom: 0;
}

::v-deep .el-tabs .el-tabs__content {
    padding: 0;
    border-bottom: 0;
}
.table-wrap {
    padding: 4px 0 0 0;
    border-bottom: 1px solid #dfe4ed;
    border-left: 1px solid #dfe4ed;
    border-right: 1px solid #dfe4ed;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
}
</style>
<style lang="scss" scoped>
.header {
    padding-bottom: 8px;
    border-bottom: 1px solid #f5f5f5;
    margin-bottom: 16px;

    .header-title {
        margin-left: 16px;
        font-size: 16px;
    }
}
.cart-content {
    display: flex;
    flex-direction: column;
    align-items: stretch;
}
::v-deep .cart-body {
    flex: 1;
    .el-checkbox__label {
        width: 0;
        padding: 0;
        color: transparent;
    }
}
.cart-header {
    padding: 8px 12px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
}
.cart-title {
    font-size: 14px;
    padding: 8px 12px;
    background-color: #ddd;
}
.cart-row {
    font-size: 14px;
    padding: 8px 12px;
    border-bottom: 1px solid #f5f5f5;
}
.cart-footer {
    padding: 8px 12px;
    border-top: 1px solid #ddd;
    display: flex;
    justify-content: center;
    align-items: center;
}
::v-deep .sub-table {
    border: 0;
    &::after {
        background: transparent;
    }
    /* 隐藏子表格的滚动条 */
    .el-table__body-wrapper {
        overflow-x: hidden !important;
    }
}

::v-deep .small-img {
    .upload-img-wrap {
        width: 54px;
    }
    .upload-img-box {
        width: 50px;
        height: 50px;
    }
    .upload-img {
        width: 48px;
        height: 48px;
    }
}
</style>
